package cn.com.longfuinfo.wx.controller;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.api.PaymentApi.TradeType;
import com.jfinal.weixin.sdk.kit.PaymentKit;

import cn.com.longfuinfo.wx.common.OrderCode;
import cn.com.longfuinfo.wx.dao.HomeBag;
import cn.com.longfuinfo.wx.dao.OrderPayAPIRecord;
import cn.com.longfuinfo.wx.dao.Recharge;
import cn.com.longfuinfo.wx.dao.User;
import cn.com.longfuinfo.wx.dao.UserCollection;
import cn.com.longfuinfo.wx.dao.UserMess;
import cn.com.longfuinfo.wx.dao.UserMoney;
import cn.com.longfuinfo.wx.dao.WxUser;
import cn.com.longfuinfo.wx.interceptor.AuthLoginInterceptor;
import cn.com.longfuinfo.wx.interceptor.RefreshLoginInterceptor;
import cn.com.longfuinfo.wx.kit.CommonKit;
import cn.com.longfuinfo.wx.kit.DatetimeKit;
import cn.com.longfuinfo.wx.kit.DoubleKit;
import cn.com.longfuinfo.wx.kit.MapKit;
import cn.com.longfuinfo.wx.service.UserService;

/**
 * 用户操作对象<br/>
 * 包括登录、注册、个人信息管理、重置密码、收藏管理、收货地址管理操作
 */
public class UserController extends BaseController {
	// 使用Duang.duang进行封装，使普通类具有事务的功能
	private Logger logger = Logger.getLogger(getClass());
	private UserService service = Duang.duang(UserService.class);

	/**
	 * 个人中心首页<br/>
	 * 限制登录状态
	 */
	// @Clear(AuthLoginInterceptor.class)
	@Before(RefreshLoginInterceptor.class)
	public void index() {
		if (getSessionAttr("userid") == "0") {
			redirect("/regist");
			return;
		}
		render("index.jsp");
	}

	/**
	 * 此方法之前，已经过滤过用户存在的情况，
	 * 此方法全新注册
	 * 保存个人资料
	 */
	public void saveInfo() {
		WxUser wxuser = getCurrentWxUser();
		if (wxuser == null) {
			logger.info("微信用户为空==异常状态=====saveInfo()===>");
			renderFailed("保存信息失败");
			return;
		}
		String sid = getPara("sid");
		String mami = getPara("mami");
		String yuchan = getPara("yuchan");
		String baby = getPara("baby");
		String phone = getPara("phone");
		String city = getPara("city");
		String name = getPara("name");
		int state = getParaToInt("state", 0);
		int times = getParaToInt("times", 0);
		int type = getParaToInt("type", 0);
		String cards = DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS");
		String card = cards.substring(2);
		//用户全新注册，如果此时用户已经存在，处于异常状态，在regist.jsp页面已经过滤用户已经存在的情况
		User userinfo = new User();
		userinfo.set("name", name).set("card", card).set("phone", phone).set("sex", type).set("state", state)
				.set("address", city).set("birthday", mami).set("novice", 1)// 入门礼为1
																			// 未领取
				.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd"));
		if (times != 0) {
			userinfo.set("taici", times);
		}
		if (StrKit.notBlank(yuchan)) {
			userinfo.set("babythday", yuchan);
			Calendar babystart = Calendar.getInstance();
			babystart.setTime(DatetimeKit.StrTooDate(yuchan));
			babystart.add(Calendar.DATE, 90);
			String babyStart = DatetimeKit.getFormatDate(babystart.getTime(), "yyyy-MM-dd");
			userinfo.set("babyStart", babyStart); // 生产礼起始日期
		}
		if (StrKit.notBlank(baby)) {
			userinfo.set("babythday", baby);
		}
		if (StrKit.notBlank(sid)) {
			logger.info("导购ID=======>"+sid);
			Record record = service.findInviteUserId(Integer.valueOf(sid));
			if (StrKit.notNull(record)) {
				userinfo.set("store", record.get("title"));
				userinfo.set("daogou", record.get("trueName"));
			}
		} else {
			logger.info("导购ID为空===>"+sid);
			userinfo.set("store", "十月妈咪河南总部");
			userinfo.set("daogou", "微商城-未扫码");
		}
		String ssx = "";
		String storeNo = "000010000100022";
		String date = DatetimeKit.getFormatDate("yyyy-MM-dd");

		// 2.0mysql数据库中是否有账号
		User users = service.findByPhone(phone);
		//2.0mysql用户存在时
		if (users != null) {
			renderResult(2);
			return;
		}else{//2.0mysql不存在时
			
			
			
			
			if(service.findVipId(phone)==null){
				//此用户管家婆也不存在时
				if (type == 1) {
					ssx = "男";
					int i = 0;
					try {
						i = service.saveVip(card, name, phone, date, storeNo, ssx);
					} catch (Exception e) {
						// TODO: handle exception
						renderResult(1);
						return;
					}
					if (i > 0) {
						Record record = service.findVipId(phone);
						String time = DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
						if (record != null) {
							try {
								service.saveVipSum(record.getInt("CardID"), time);
							} catch (Exception e) {
								// TODO: handle exception
								renderResult(1);
								return;
							}
						}
					}
				} else {
					ssx = "女";
					int i = service.saveVip(card, name, phone, date, storeNo, ssx);
					if (i > 0) {
						Record record = service.findVipId(phone);
						String time = DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
						if (record != null) {
							try {
								service.saveVipSum(record.getInt("CardID"), time);
							} catch (Exception e) {
								// TODO: handle exception
								renderResult(1);
								return;
							}
						}

					}
				}
//				保存mysql2.0  此用户
				userinfoSave(userinfo,wxuser,phone);
			}else{
				logger.info("管家婆此用户已经注册====");
				//管家婆此用户已经注册
				userinfoSave(userinfo,wxuser,phone);
				
			}
			
			
		}
		
	}
	/**
	 * 保存mysql2.0库用户，并关联微信
	 * @param userinfo
	 * @param wxUser
	 * @param phone
	 */
	public void userinfoSave(User userinfo,WxUser wxUser,String phone) {
		if (userinfo.save()) {
			// 2.0注册成功，关联微信
			User newUsers = service.findByPhone(phone);
			if (newUsers != null) {
				newUsers.set("guanzhu", 2).update();
				/* 关联微信 */
				wxUser.set("userid", newUsers.getInt("id"));
			}
			if (wxUser.update()) {
				setSessionAttr("userid", newUsers.getInt("id"));
				renderSuccess();
				return;
			} else {
				renderFailed("保存信息失败");
				return;
			}
			
		} else {
			renderFailed("保存信息失败");
			return;
		}
	}

	/**
	 * 查询当前登录用户各状态信息<br/>
	 * 分别统计“收藏商品数量”、“待付款”、“待兑换”、“已兑换”、“已过期”五种状态的订单数量
	 */
	public void state() {
		Record state = service.getUserState(getCurrentWxUserid());
		renderSuccess(MapKit.one().put("collected", state.get("state1")).put("noPay", state.get("state2"))
				.put("noTake", state.get("state3")).put("noEval", state.get("state4"))
				.put("noDel", state.get("state5")));
	}

	/**
	 * 跳转我的钱包
	 * 
	 */
	public void myWallet() {
		WxUser user = getCurrentWxUser();
		if (user == null) {
			redirect("/index");
			return;
		} else {
			User users = service.findByUserid(user.getInt("id"));
			setAttr("money", users.get("money"));
			render("myWallet.jsp");
		}
	}

	/* 充值 */
	public void topoint() {
		WxUser user = getCurrentWxUser();
		if (user == null) {
			redirect("/index");
			return;
		} else {
			String chargeNum = "CZ" + DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS") + CommonKit.randomNum(2);
			Recharge rec = new Recharge();
			rec.set("chargeNum", chargeNum).set("userid", user.getInt("id"));
			// 获取调用微信js接口所需要的参数
			if (rec.save()) {
				getJSApiParams(PropKit.get("constants.url_prev") + "/my/topoint");
				setAttr("chargeNum", chargeNum);
				render("point.jsp");
				return;
			}
		}
	}

	/**
	 * 微信充值
	 */
	public void paymkttransfers() {
		WxUser wxUser = getCurrentWxUser();
		// 判断当前登录用户是否已授权
		if (wxUser == null) {
			renderResult(1);
			return;
		}
		String orderNum = getPara("chargeNum");
		String flagStr = getPara("flag");
		String amounts = getPara("amount");
		int paytype = Integer.valueOf(flagStr);
		if (paytype == OrderCode.OrderPayMethod.WEIXIN) {
			// 计算订单总金额
			double amount = Double.valueOf(amounts);
			// 获取订单总金额，并转换为以“分”为单位
			String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount, 100)).intValue()).toString();
			// openId，采用 网页授权获取 access_token API：SnsAccessTokenApi获取
			String openId = wxUser.getStr("openid");
			// 统一下单文档地址：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
			Map<String, String> params = new HashMap<String, String>();
			params.put("appid", PropKit.get("wx.pay.appId"));
			params.put("mch_id", PropKit.get("wx.pay.mch_id"));
			params.put("body", "OK妈咪微信商城");
			params.put("out_trade_no", orderNum);
			params.put("total_fee", amountStr);// 总金额单位为分
			String ip = CommonKit.getClientIp(getRequest());
			if (StrKit.isBlank(ip)) {
				ip = "127.0.0.1";
			}
			params.put("spbill_create_ip", ip);
			params.put("trade_type", TradeType.JSAPI.name());
			params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
			params.put("notify_url", PropKit.get("wx.pay.notifyUrl"));
			params.put("openid", openId);
			// 生成签名
			params.put("sign", PaymentKit.createSign(params, PropKit.get("wx.pay.key")));
			logger.error(params.toString());
			// 统一下单
			String xmlResult = PaymentApi.pushOrder(params);
			// 保存接口请求和响应内容日志
			new OrderPayAPIRecord().set("orderNum", orderNum).set("sendContent", params.toString())
					.set("returnContent", xmlResult).set("payMethod", paytype).set("flag", 2).save();
			// 根据响应结果给页面响应
			Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
			String return_code = result.get("return_code");
			String return_msg = result.get("return_msg");
			if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
				renderResult(3, return_msg);
				return;
			}
			String result_code = result.get("result_code");
			String result_msg = result.get("err_code_des");
			if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
				renderResult(4, result_msg);
				return;
			}
			// 以下字段在return_code 和result_code都为SUCCESS的时候有返回
			String prepay_id = result.get("prepay_id");
			// 将结果响应给页面以进行下一步操作
			Map<String, String> packageParams = new HashMap<String, String>();
			packageParams.put("appId", PropKit.get("wx.pay.appId"));
			packageParams.put("timeStamp", System.currentTimeMillis() / 1000 + "");
			packageParams.put("nonceStr", System.currentTimeMillis() + "");
			packageParams.put("package", "prepay_id=" + prepay_id);
			packageParams.put("signType", "MD5");
			packageParams.put("paySign", PaymentKit.createSign(packageParams, PropKit.get("wx.pay.key")));
			// 将页面调用微信所需要的参数返回给页面
			renderSuccess(packageParams);
			return;
		}
		renderFailed("支付错误");
		return;
	}

	/**
	 * 跳转到联系我们页面
	 */
	public void connection() {
		render("connection.jsp");
	}

	/**
	 * 用户收藏指定商品
	 * 
	 * @param goodsid
	 *            商品ID
	 */
	public void doCollect() {
		String goodsidStr = getPara("goodsid");
		if (StrKit.isBlank(goodsidStr)) {
			renderFailed("参数GOODSID不能为空");
			return;
		}
		// 收藏
		if (getCurrentWxUser() != null) {
			UserCollection c = service.doCollect(getCurrentWxUserid(), goodsidStr);
			renderSuccess(MapKit.one().put("isCancel", c.getInt("isCancel")).getAttrs());
		} else {
			redirect("/index");
			return;
		}

	}

	/**
	 * 个人资料
	 */
	public void myinfo() {
		WxUser user = getCurrentWxUser();
		if (user == null) {
			redirect("/index");
			return;
		} else {
			User userinfo = service.getUserInfo(user.getInt("id"));
			setAttr("userInfo", userinfo);
			render("personinfo.jsp");
		}
	}

	/**
	 * 我的消息
	 */
	public void mymess() {
		WxUser user = getCurrentWxUser();
		if (user == null) {
			redirect("/index");
			return;
		} else {
			/*
			 * List<UserMess>mess=service.findMess(user.getInt("id")); for
			 * (UserMess userMess : mess) { userMess.set("state", 2).update(); }
			 */
			render("mess.jsp");
		}
	}

	public void mess() {
		Record state = service.getUserState2(getCurrentWxUserid());
		renderSuccess(MapKit.one().put("mess", state.get("mess")));
	}

	public void messList() {
		int pageNum = getParaToInt("pageNum", 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		Page<UserMess> page = service.findMessByPage(getCurrentWxUserid(), pageNum, pageSize);
		renderSuccess(page);
		return;
	}

	/**
	 * 修改消息状态
	 */
	public void messState() {
		int id = getParaToInt("id", 0);
		UserMess mess = service.findMessage(id);
		mess.set("state", 2);
		if (mess.update()) {
			renderSuccess();
			return;
		}
	}

	/**
	 * 用户删除消息
	 * 
	 * @param goodsid
	 *            商品ID
	 */
	public void cancelMess() {
		String messidsStr = getPara("messid");
		if (StrKit.isBlank(messidsStr)) {
			renderFailed("参数messidsStr不能为空");
			return;
		}
		String[] messids;
		if (messidsStr.indexOf(",") >= 1) {
			messids = messidsStr.split(",");
		} else {
			messids = new String[] { messidsStr };
		}
		// 批量删除消息
		service.cancelMess(getCurrentWxUserid(), messids);
		renderSuccess();
	}

	/**
	 * 用户取消收藏指定商品
	 * 
	 * @param goodsid
	 *            商品ID
	 */
	public void cancelCollect() {
		String goodsidsStr = getPara("goodsid");
		if (StrKit.isBlank(goodsidsStr)) {
			renderFailed("参数GOODSID不能为空");
			return;
		}
		String[] goodsids;
		if (goodsidsStr.indexOf(",") >= 1) {
			goodsids = goodsidsStr.split(",");
		} else {
			goodsids = new String[] { goodsidsStr };
		}
		// 批量取消收藏
		service.cancelCollect(getCurrentWxUserid(), goodsids);
		renderSuccess();
	}

	public void collection() {
		render("collection.jsp");
	}

	/**
	 * 分页查询用户收藏商品列表
	 * 
	 * @param pageNum
	 *            页码
	 * @param pageSize
	 *            数量
	 */
	public void collectionList() {
		int pageNum = getParaToInt("pageNum", 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderSuccess(service.findCollectionByPage(getCurrentWxUserid(), pageNum, pageSize));
	}

	@Clear(AuthLoginInterceptor.class)
	public void history() {
		render("history.jsp");
	}

	/**
	 * 删除消息
	 */
	public void deleteMess() {
		int id = getParaToInt("id", 0);
		WxUser user = getCurrentWxUser();
		if (user == null) {
			redirect("/index");
			return;
		} else {
			UserMess mess = service.findMessage(id);
			if (StrKit.notNull(mess)) {
				if (mess.delete()) {
					renderSuccess();
					return;
				} else {
					renderFailed("消息删除失败");
					return;
				}
			} else {
				renderFailed("消息不存在");
				return;
			}
		}
	}

	/**
	 * 货币变更记录
	 */
	public void moneyChange() {
		int pageNum = getParaToInt("pageNum", 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		WxUser user = getCurrentWxUser();
		if (user == null) {
			redirect("/index");
			return;
		} else {
			Page<UserMoney> page = service.findMoneyChange(pageNum, pageSize, user.getInt("id"));
			renderSuccess(page);
		}
	}

	/**
	 * 余额明细
	 */
	public void balanceDetail() {
		WxUser user = getCurrentWxUser();
		if (user == null) {
			redirect("/index");
			return;
		} else {
			List<UserMoney> balanceList = service.findbalanceDetail(user.getInt("id"));
			setAttr("balanceList", balanceList);
			render("balance.jsp");
		}
	}

	/**
	 * 联系我们
	 */
	public void mycon() {
		render("lianxiwomen.html");
	}

	/**
	 * 新手帮助
	 */
	public void help() {
		render("help.html");
	}

	/**
	 * 关于我们
	 */
	public void forus() {
		render("guanyuwomen.html");
	}

	/**
	 * 会员权益
	 */
	public void vipEquity() {
		render("vipequity.html");
	}

	/**
	 * 领取礼包
	 */
	public void homeBag() {
		System.out.println("礼包领取");
		int pushDateType = getParaToInt("type");
		int giftid = getParaToInt("id");
		WxUser user = getCurrentWxUser();
		if (user == null) {
			redirect("/index");
			return;
		} else {
			User userinfo = service.getUserInfo(user.getInt("id"));
			if (pushDateType == 3)
				userinfo.set("novice", 0).update();
			if (pushDateType == 2)
				userinfo.set("babyBag", 2).update();
			if (pushDateType == 1) {
				Calendar now = Calendar.getInstance();
				String year = userinfo.getStr("giftYear");
				if (year == null)
					userinfo.set("birthBag", 0).set("giftYear", now.get(Calendar.YEAR)).update();
				else
					userinfo.set("birthBag", 0).set("giftYear", (now.get(Calendar.YEAR) + "," + year)).update();
			}
			HomeBag homebag = HomeBag.me().findById(giftid);
			homebag.set("receive", homebag.getInt("receive") + 1).update();
			service.giftlog(userinfo.getInt("id"), giftid, pushDateType);
			/* redirect("/index"); */
			renderSuccess();
			return;
		}

	}

	/**
	 * 关闭礼包
	 */
	public void closeBag() {
		int giftid = getParaToInt("id");
		HomeBag homebag = HomeBag.me().findById(giftid);
		homebag.set("closeNum", homebag.getInt("closeNum") + 1).update();
	}
}